import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HttpStudy extends StatefulWidget {
  const HttpStudy({super.key});

  @override
  State<HttpStudy> createState() => _HttpStudyState();
}

class _HttpStudyState extends State<HttpStudy> {
  var resultShow = '';
  var resultShow2 = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Http实现网络操作')),
      body: Column(children: [_doGetBtn(), _doPostBtn(), _doPostJsonBtn(), Text("返回结果：$resultShow"), Text("返回结果：$resultShow2")]),
    );
    // return const Placeholder();
  }

  _doGetBtn () {
    return ElevatedButton(onPressed: _doGet, child: const Text('发送Get请求'));
  }

  _doPostBtn () {
    return ElevatedButton(onPressed: _doPost, child: const Text('发送Post请求'));
  }

  _doPostJsonBtn () {
    return ElevatedButton(onPressed: _doPostJson, child: const Text('发送PostJson请求'));
  }

  // 发送get请求
  void _doGet() async {
    var uri = Uri.parse('https://api.devio.org/uapi/test/test?requestPrams=11');
    var response = await http.get(uri);
    if (response.statusCode == 200) {
      setState(() {
        resultShow = response.body;
      });
    } else {
      setState(() {
        resultShow = '请求失败，状态码：${response.statusCode}';
      });
    }
  }

  _doPost () async {
    var uri = Uri.parse('https://api.devio.org/uapi/test/test');
    var prams = {
      "requestPrams": "doPost"
    };
    var response = await http.post(uri, body: prams);
    if (response.statusCode == 200) {
      setState(() {
        resultShow = response.body;
      });
    } else {
      setState(() {
        resultShow = '请求失败，状态码：${response.statusCode}';
      });
    }
  }
  // 发送json类型的post请求
  _doPostJson () async {
    var uri = Uri.parse('https://api.devio.org/uapi/test/testJson');
    var prams = {
      "requestPrams": "doPostJson"
    };
    var response = await http.post(uri, body: jsonEncode(prams), headers: {
      "content-type": "application/json"
    });
    if (response.statusCode == 200) {
      setState(() {
        resultShow = response.body;
      });
      var map = jsonDecode(response.body);
      setState(() {
        resultShow2 = map['msg'];
      });

    } else {
      setState(() {
        resultShow = '请求失败，状态码：${response.statusCode}';
      });
    }
  }
}
